package my.edu.model.User.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.DeleteJoinWrapper;
import my.edu.common.constant.MessageConstant;
import my.edu.common.exception.CanNotFoundException;
import my.edu.model.User.entity.Permission;
import my.edu.model.User.entity.dto.PermissionDTO;
import my.edu.model.User.entity.dto.RoleDTO;
import my.edu.model.User.mapper.RolePermissionMapper;
import my.edu.model.User.entity.RolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Autowired
    private IPermissionService permissionService;


    @Override
    public void removeByRoleId(Long roleId) {
        DeleteJoinWrapper<RolePermission> wrapper = JoinWrappers.delete(RolePermission.class);
        wrapper
                .eq(RolePermission::getRoleId, roleId);
        baseMapper.deleteJoin(wrapper);
    }



    @Override
    @Transactional
    public void saveBatchByRoleIAndName(Long roleId, List<String> permissionNameList) {
        List<Permission> permissionList = permissionService.list(Wrappers.<Permission>lambdaQuery().in(Permission::getName, permissionNameList));
        List<Long> permissionIdList = permissionList.stream().map(Permission::getId).toList();
        List<RolePermission> rolePermissionList = permissionIdList.stream().map(permissionId -> new RolePermission(roleId, permissionId)).toList();
        saveBatch(rolePermissionList);
    }

    @Override
    @Transactional
    public void saveBatchByRoleIAndPermissionId(Long id, List<PermissionDTO> dtoPermissionList) {
        List<RolePermission> rolePermissionList = dtoPermissionList.stream().map(dtoPermission -> new RolePermission(id, dtoPermission.getId())).toList();
        saveBatch(rolePermissionList);
    }
}
